package test.transferFile.codec;

import java.nio.charset.Charset;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import test.transferFile.common.MyBuffer;
import test.transferFile.common.MyFile;

public class TransferFileEncoder extends ProtocolEncoderAdapter {

  private Charset charset;

  public void setCharset(Charset charset) {
    this.charset=charset;
  }

  public Charset getCharset() {
    return charset;
  }

  public TransferFileEncoder(Charset charset) {
    this.charset=charset;
  }

  @Override
  public void encode(IoSession session, Object obj, ProtocolEncoderOutput out) throws Exception {
    MyFile myFile=(MyFile)obj;
    MyBuffer myBuf=MyBuffer.allocate(2048);
    myBuf.putString(myFile.getName());// name
    myBuf.putInt(myFile.getLength());// length
    myBuf.putInt(myFile.getPos());// pos
    myBuf.put(myFile.getData());// data
    myBuf.flip();
    System.out.println("编码拆分包:" + myBuf);
    out.write(myBuf.getIoBuffer());
  }
}
